<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{path:'/home'}">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item :to="{path:'/goods'}">商品列表</el-breadcrumb-item>
            <el-breadcrumb-item>添加商品</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片视图 -->
        <el-card>
            <el-steps :active="parseInt(activeStep)" finish-status="success" align-center>
                <el-step title="基本信息"></el-step>
                <el-step title="商品参数"></el-step>
                <el-step title="商品属性"></el-step>
                <el-step title="商品图片"></el-step>
                <el-step title="商品内容"></el-step>
                <el-step title="完成"></el-step>
            </el-steps>
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="120px">
            <el-tabs tab-position="left" v-model="activeStep" @tab-click="tabClick" :before-leave="beforeTabChange">
                <el-tab-pane label="基本信息" name="0">
                    <el-form-item label="商品名称" prop="goods_name">
                        <el-input v-model="addForm.goods_name"></el-input>
                    </el-form-item>
                    <el-form-item label="商品价格" prop="goods_price">
                        <el-input-number :min="0" v-model="addForm.goods_price"></el-input-number>
                    </el-form-item>
                    <el-form-item label="商品重量" prop="goods_weight">
                        <el-input-number :min="0" v-model="addForm.goods_weight"></el-input-number>
                    </el-form-item>
                    <el-form-item label="商品数量" prop="goods_number">
                        <el-input-number :min="1" v-model="addForm.goods_number"></el-input-number>
                    </el-form-item>
                    <el-form-item label="商品分类" prop="goods_cat">
                        <el-cascader
                            v-model="selectedCatIds"
                            clearable
                            expandTrigger="hover"
                            :options="cateList"
                            :props="{ value: 'cat_id', label: 'cat_name'}"
                        ></el-cascader>
                    </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="商品参数" name="1">
                    <el-form-item :label="item.attr_name" v-for="item in attrList" :key="item.attr_id">
                        <el-checkbox-group v-model="item.attr_vals">
                            <el-checkbox border v-for="(val,index) in item.attr_vals" :key="index" :label="val"></el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="商品属性" name="2">
                    <el-form-item :label="item.attr_name" v-for="item in attrList2" :key="item.attr_id">
                        <el-input v-model="item.attr_vals"></el-input>
                    </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="商品图片" name="3">
                    <el-upload
                        class="upload-demo"
                        :action="uploadUrl"
                        :headers="headerObject"
                        :on-success="handleSuccess"
                        :on-preview="handlePreview"
                        :on-remove="handleRemove"
                        list-type="picture">
                        <el-button size="small" type="primary">点击上传</el-button>
                        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
                    </el-upload>
                </el-tab-pane>
                <el-tab-pane label="商品内容" name="4">
                    <quill-editor v-model="addForm.goods_introduce"
                        :options="quillEditorOption"
                    ></quill-editor>
                    <div style="margin-top:16px;">
                        <el-button type="primary" @click="add">保存商品</el-button>
                    </div>
                </el-tab-pane>
            </el-tabs>
            </el-form>
        </el-card>
        <el-dialog :visible.sync="previewOn" title="预览">
            <img :src="previewUrl" style="width:100%;">
        </el-dialog>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                uploadUrl: process.env.VUE_APP_API+'upload',
                headerObject: {
                    Authorization: window.sessionStorage.getItem('token')
                },
                activeStep: '0',
                cateList: [],
                attrList: [],
                attrList2: [],
                selectedAttrList: [],
                previewOn: false,
                previewUrl: '',
                addForm: {
                    goods_name: '',
                    goods_price: 0,
                    goods_weight: 0,
                    goods_number: 1,
                    goods_introduce: '',
                    goods_cat: [],
                    pics: []
                },
                selectedCatIds: [],
                selectedAttrs: [],
                addFormRules: {
                    goods_name: [
                        { required:true ,trigger: 'blur', message: '请输入名称'},
                        { max: 256 ,trigger: 'blur', message: '最长256字符'},
                    ],
                    goods_price: { required:true ,trigger: 'blur', message: '请输入价格'},
                    goods_weight: { required:true ,trigger: 'blur', message: '请输入重量'},
                    goods_number: { required:true ,trigger: 'blur', message: '请输入数量'}
                },
                quillEditorOption: {
                    theme: 'snow',
                    placeholder: '请输入商品描述信息',
                   
                }
            }
        },
        created() {
            this.getCatList();
        },
        methods: {
            async getCatList() {
                const { data: res} = await this.$http.get('categories');
                if(res.meta.status!=200) {
                    return this.$message.error('获取商品分类失败！'+res.meta.msg);
                }
                this.cateList=res.data;
                console.log('cates',res.data);
            },
            beforeTabChange(activeName, oldActiveName) {
                console.log(oldActiveName,activeName);
                if(oldActiveName==0&&this.selectedCatIds.length==0) {
                    this.$message.warning('请先选择商品分类');
                    return false;
                }
            },
            async tabClick() {
                if(this.activeStep=='1')
                {
                    if(this.selectedCatId)
                    {
                        const { data: res} = await this.$http.get('categories/'+this.selectedCatId+'/attributes',
                            {params: {sel: 'many'}});
                        if(res.meta.status!=200) {
                            return this.$message.error('获取分类参数失败！'+res.meta.msg);
                        }
                        this.attrList=res.data;
                        this.attrList.forEach(attr=>{
                            if(attr.attr_vals)
                                attr.attr_vals=attr.attr_vals.split(',');
                            else
                                attr.attr_vals=[];
                        });
                    }
                    else
                        this.attrList=[];
                }
                else if(this.activeStep=='2')
                {
                    if(this.selectedCatId)
                    {
                        const { data: res} = await this.$http.get('categories/'+this.selectedCatId+'/attributes',
                            {params: {sel: 'only'}});
                        if(res.meta.status!=200) {
                            return this.$message.error('获取分类属性失败！'+res.meta.msg);
                        }
                        this.attrList2=res.data;
                    }
                    else
                        this.attrList2=[];
                }
            },
            handleSuccess(res) {
                console.log('upload over',res);
                this.addForm.pics.push({pic: res.data.tmp_path});
            },
            handlePreview(file) {
                this.previewUrl=file.response.data.url;
                this.previewOn=true;
            },
            handleRemove(file) {
                const idx=this.addForm.pics.findIndex(pic=>pic.pic==file.response.data.tmp_path);
                if(idx!=-1) this.addForm.pics.splice(idx,1);
            },
            add() {
                this.$refs.addFormRef.validate(async (valid,err)=> {
                    if(!valid) {
                        console.log('valid',err);
                        return this.$message.error('请先填写必要的表单项！'); 
                    }
                    //填充goods_cat
                    this.addForm.goods_cat=this.selectedCatIds.join(',');                    
                    this.addForm.attrs=[];
                    //动态attr
                    this.attrList.forEach(attr => {
                        if(attr.attr_vals.length>0)
                        attr.attr_vals.forEach(val=>{
                            if(val)
                            this.addForm.attrs.push({
                                attr_id: attr.attr_id,
                                attr_value: val
                            });
                        });
                    });
                    //静态attr
                    this.attrList2.forEach(attr => {
                        if(attr.attr_vals)
                            this.addForm.attrs.push({
                                attr_id: attr.attr_id,
                                attr_value: attr.attr_vals
                            });
                    });
                    console.log('addForm',this.addForm);
                    const {data:res} = await this.$http.post('goods',this.addForm);
                     if(res.meta.status!=201) {
                            return this.$message.error('添加商品失败！'+res.meta.msg);
                    }
                    this.$message.success('添加商品成功！');
                    this.$router.push('/goods')
                });
            }
        },
        computed: {
            selectedCatId() {
                if(this.selectedCatIds.length>0)
                    return this.selectedCatIds[this.selectedCatIds.length-1];
            }
        }
    }
</script>

<style lang="less" scoped>
.el-checkbox {
    margin: 0 10px 0 0 !important;
}


</style>